﻿
$(document).ready(function () {
	$('#groupfields ul').hide();
	$('#groupfields ul:first').show();
	$('#grouptab span:first').addClass('current');
	$('#grouptab span a').click(function () {
		// Focus current tab
		$('#grouptab span').removeClass('current');
		$(this).parent().addClass('current');

		// Show current group
		var currentTab = $(this).attr('href');
		$('#groupfields ul').hide();
		$(currentTab).show();

		return false;
	});

    // Disabler
    $('#toolbar1, #groupform').disabler();

    if ($('#leadTypeSelected').val() == "" || $('#leadSourceSelected').val() == "" || $('#leadSourceSelected').val() == "all") {
        //console.log('show');
        $('.disabler').show();
    }
    else {
        //console.log('hide');
        $('.disabler').hide();
    }

	// Collspan/ Expand
	$('ul.accordeon-tabs li').each(function () {
		$(this).find(".tab").click(function () {
			if ($(this).parent().attr("class") == "open") {
				$(this).parent().removeClass("open");
				$(this).parent().addClass("close");
				$(this).parent().find(".panel").css("display", "none");
			}
			else {
				$(this).parent().removeClass("close");
				$(this).parent().addClass("open");
				$(this).parent().find(".panel").css("display", "block");
			}
		});
	});

	$(".calendar-date").datepicker();
	$(".calendar-time").timepicker();
	$(".start-time").timepicker();
	$(".calendar-datetime").datetimepicker();
	$(".cal").datepicker();
});

var addLeadViewModel = new function () {
    this.LeadType = ko.observable(data.LeadTypeId);
	this.LeadTypeOptions = ko.observableArray(data.LeadType);
	this.LeadSource = ko.observable(data.LeadSourceId);
	this.LeadSourceOptions = ko.observableArray(data.LeadSource);
	this.User = ko.observable(data.UserId);
	this.UserOptions = ko.observableArray(data.UserFilter);

	// Add new requirement
	this.EnableLeadType = ko.computed(function () {
	    return !(!this.LeadTypeOptions() || !this.LeadTypeOptions().length || this.LeadTypeOptions().length <= 1);
	}, this);
	this.PleaseMessage = ko.computed(function () {
	    return this.EnableLeadType() ? "Xin hãy chọn loại và nguồn khách hàng để bật biểu mẫu dưới."
			: "Xin hãy chọn guồn khách hàng để bật biểu mẫu dưới.";
	}, this);

	this.LeadTypeAndSourceAreValid = ko.computed(function () {
	    var leadTypeId = parseInt(this.LeadType()),
			leadSourceId = parseInt(this.LeadSource());

	    var validateOptions = (!isNaN(leadSourceId) && leadSourceId > 0
			&& (!this.EnableLeadType() || (!isNaN(leadTypeId) && leadTypeId > 0)));

	    if (validateOptions) {
	        $(".disabler").hide();
	    }
	    else {
	        $(".disabler").show();
	    }

	    return validateOptions;
	}, this);

	this.EnableMessage = ko.computed(function () {
	    return !this.LeadTypeAndSourceAreValid();
	}, this);

	this.toolbarClass = ko.computed(function () {
	    return (!this.LeadTypeAndSourceAreValid()) ? "toolbar errors" : "toolbar";
	}, this);
};


$(document).ready(function () {
    if ($("#LeadType option").length > 1) {

        $("#LeadType, #LeadSource").change(function () {
            //console.log($(this).val());
            var leadTypeId = $("#LeadType").val(),
				leadType = parseInt(leadTypeId),
				leadTypeSelected = $("#leadTypeSelected").val(),
				leadSource = parseInt($("#LeadSource").val());

            if (leadTypeId !== leadTypeSelected && !isNaN(leadSource) && leadSource > 0) {
                // Show waiting dialog while redirecting
                $(".fancybox-skin, #fancybox-overlay").show();
                $.fancybox($("#popup-sumitting"), {
                    padding: 0,
                    closeBtn: false,
                    helpers: {
                        overlay: {
                            opacity: 0.6,
                            css: { "background-color": "#11619D" }
                        }
                    },
                    beforeClose: function () { return false; }
                });

                window.location = "/Lead/Add?id="
					+ ((!isNaN(leadType) && leadType > 0) ? leadType.toString() : "") + "&sourceId=" + leadSource;
            }
        });
    }

    //$("form").validate({ submitHandler: addLeadViewModel.Submit });
    $("form#myForm").validation();
    $("form#myForm #errorMessages").hide();

});

// We can check if the form is valid on demand, using our validate function.
function preValidateLeadForm(inp) {
	var $form = $(inp).closest("form");

	// Lead Type and Lead Source are required
	var isValid = false,
		leadSourceId = parseInt($form.find("#toolbargroup .sel-lead-source select:first").val()),
		leadTypeId = parseInt($form.find("#toolbargroup .sel-lead-type input[name='LeadType']").val());

	if (!isNaN(leadSourceId) && leadSourceId > 0) {

	    if (!$form.find("#toolbargroup .sel-lead-type select:first option").length
			|| (!isNaN(leadTypeId) && leadTypeId > 0)) {

	        isValid = true;
	    }
	}

	if (isValid) {
	    var groupErrorMessage = $form.find("#errorMessages");

	    console.log('valid select');

	    if ($form.validate()) {
	        groupErrorMessage.hide();
	        $(".fancybox-skin, #fancybox-overlay").show();

	        $.fancybox($("#popup-sumitting"), {
	            padding: 0,
	            closeBtn: false,
	            helpers: {
	                overlay: {
	                    opacity: 0.6,
	                    css: {
	                        'background-color': '#11619D'
	                    }
	                }
	            },
	            beforeClose: function () {
	                return false;
	            }
	        });

	        return true;
	    }
	    else {
	        // Add Error
	        groupErrorMessage.find(".errorgrid").html('<strong>Lỗi: Dữ liệu không hợp lệ</strong><span>Mẫu đơn này đã không được lưu, hãy sửa chữa các lỗi sau đây:<br /></span><ul class="errorlist" style="margin-top:10px; margin-left:20px"></ul>');

	        // Find error messages
	        $form.find("#grouptab a.nexttab").each(function () {
	            var $lnk = $(this),
					tabName = $lnk.text();

	            $("ul" + $lnk.attr("href").replace(/^.*?#+/g, "#") + " li").each(function () {
	                $(this).find(".error-desc").each(function () {
	                    groupErrorMessage.find(".errorlist").append("<li>" + tabName + " &raquo; " + $(this).html() + "</li>");
	                });
	            });
	        });

	        groupErrorMessage.show();
	    }
	}

	return false;
}

// Apply view model
addLeadViewModel.errors = ko.validation.group(addLeadViewModel);
ko.applyBindings(addLeadViewModel, document.getElementById("main"));
